<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form ref="div" :inline="true" label-width="110px" :model="searchForm" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="关键字">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                placeholder="输入名称或手机号"></el-input>
            </el-form-item>
            <el-form-item label="角色权限">
              <el-select filterable @change="onSearch(1)" v-model="searchForm.role_id" clearable placeholder="选择角色"
                class="form-width">
                <el-option v-for="(item, idx) in roleList" :label="item.name" :value="item.id" :key="idx"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <!-- <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p> -->
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addUserModel"
            v-if="$isPer(permission, ['admin_addAdmin'])">添加品牌方</el-button>
        </div>
      </div>
    </div>

    <!-- 列表 -->
    <div class="page-list" ref="pageList" v-loading="loading">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
        </p>
        <div class="list-top-box-right">
          <el-button style="opacity: 0;"></el-button>


          <el-button type="primary" v-if="$isPer(permission, ['admin_removeLoginRestrictions'])
          " @click="editEven(multipleSelection[0], 'removeUserLoginRest')"
            :disabled="multipleSelection.length != 1 || (multipleSelection[0] && multipleSelection[0].login_fail_num < 3)">解锁登录</el-button>
          <el-button type="primary" v-if="$isPer(permission, ['admin_resetPassword'])"
            @click="resetPwd(multipleSelection[0])" :disabled="multipleSelection.length != 1">重置密码</el-button>
          <el-button type="primary" :disabled="multipleSelection.length != 1"
            @click="editEven(multipleSelection[0], 'admin_updateAdmin')"
            v-if="$isPer(permission, ['admin_updAdmin'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0"
            @click="editEven('', 'admin_deleteAdmin')" v-if="$isPer(permission, ['admin_delAdmin'])">删除</el-button>
        </div>
      </div>
      <!-- stripe -->
      <div class="table-box">
        <el-table ref="table" height="100%" :data="tableData" style="width: 100%" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column prop="" label="头像" width="80">
            <template slot-scope="scope">
              <img class="avatar-itme" :src="scope.row.image" />
            </template>
          </el-table-column>
          <el-table-column min-width="180px" prop="" label="用户名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="name-item">{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" prop="phone" label="用户账号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="brand_name" label="归属品牌" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column min-width="180px" show-overflow-tooltip prop="position" label="职务">
          </el-table-column> -->
          <el-table-column min-width="180px" show-overflow-tooltip prop="role_name" label="角色权限">
          </el-table-column>
          <!-- <el-table-column min-width="180px" show-overflow-tooltip prop="updated_at" label="更新时间">
          </el-table-column> -->
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page-footer">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-size="num"
          :current-page.sync="page" :total="total" @current-change="pageChange" @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog destroy-on-close :title="userFormType == 'add' ? '添加用户' : '修改用户'" :visible.sync="dialogFormVisible"
      @close="saveUserClose" :close-on-click-modal="false" width="460px">
      <el-form :model="userForm" :rules="userRules" class="user-info" ref="userFrom" label-width="110px"
        label-position="left">
        <el-form-item label="用户头像">
          <el-upload action="#" list-type="picture-card" :show-file-list="false" :on-change="change_file"
            accept=".png,.jpeg,.jpg,.webp" :auto-upload="false">
            <img v-if="userForm.imgUrl" :src="userForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input clearable v-model="userForm.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input maxlength="11" clearable v-model="userForm.phone" type="number"
            oninput="if(value.length > 11) value=value.slice(0, 11)" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="userFormType == 'add'">
          <el-input clearable v-model="userForm.password" placeholder="请输入登录密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="所属城市" prop="city">
          <el-cascader v-model="userForm.city" :options="cityList" placeholder="请选择所属城市" clearable
            :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
          </el-cascader>
        </el-form-item>
        <el-form-item label="品牌" prop="brand_id">
          <el-select filterable clearable v-model="userForm.brand_id" placeholder="请选择品牌">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select filterable clearable v-model="userForm.role_id" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit('userFrom')" :loading="submitBtn">提交</el-button>
        <el-button @click="saveUserClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import permissionApi from "@/api/permissionApi";
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import adminApi from "@/api/adminApi";
import brandApi from "@/api/brandApi";

export default {
  name: "userList",
  data() {
    var password = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/.test(value)) {
        callback(new Error("密码须8-16位,包含大小写字母、数字"));
      } else {
        callback();
      }
    };
    var phoneRule = (rule, value, callback) => {
      if (!/^1\d{10}$/.test(value)) {
        return callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    return {
      permission: [],//页面操作权限
      loading: false,//页面加载loading
      moreSearchShow: false,//搜索显示/隐藏
      searchForm: {
        keyword: '',
        role_id: '',
      },//搜索form
      multipleSelection: [],//多选列表
      tableData: [],//列表数据
      total: 0,//列表数据总数
      page: 1,//页码
      num: 10,//条数
      // 添加人员
      dialogFormVisible: false,//弹窗显示/隐藏
      userFormType: "add",//弹窗修改/添加
      userForm: {
        admin_id: "",
        name: "",
        imgUrl: "",
        imgFile: null,
        phone: "",
        password: "",
        position_id: "",
        brand_id: "",
        role_id: "",
        city: [],
        discount_ratio: "",
        settlement_discount_ratio: "",
        engineering_supervision_id: "",
      },//添加人员form
      userRules: {
        imgUrl: [
          {
            required: true,
            message: "请上传头像",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            validator: phoneRule,
            trigger: "change",
          },
        ],
        password: [
          {
            validator: password,
            required: true,
            trigger: "change",
          },
        ],
        city: [
          {
            required: true,
            message: "请选择所属城市",
            trigger: "change",
          },
        ],
        role_id: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
      },//添加人员规则
      cityList: [],//省市区数据
      userInfo: {},//登陆者信息
      roleList: [],//角色列表
      submitBtn: false,//添加人员弹窗loading
      brandList: [], //品牌列表
    };
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.getAreaList();//省市区
    this.userInfo = getUserInfo();//登陆者信息
    this.getRoleList();//角色列表
    this.getAdminList();//用户列表
    this.getBrandList();//品牌列表
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    // 页数改变
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 条数改变
    pageChange(page) {
      this.onSearch(page);
    },
    // table多选事件
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 添加人员弹窗关闭
    saveUserClose() {
      this.userForm = {
        admin_id: "",
        name: "",
        imgUrl: "",
        imgFile: null,
        phone: "",
        password: "",
        position_id: "",
        brand_id: "",
        role_id: "",
        city: [],
        discount_ratio: "",
        settlement_discount_ratio: "",
        engineering_supervision_id: "",
      };
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
        this.dialogFormVisible = false;
      });
    },
    // 选择用户头像
    change_file(e) {
      this.userForm.imgUrl = e.url;
      this.userForm.imgFile = e.raw;
    },
    // 获取角色列表
    getRoleList() {
      permissionApi
        .getRoleList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "角色列表");
          if (res.code == 200) {
            this.roleList = res.data.list;
          }
        });
    },
    // 省市区
    getAreaList() {
      commonApi.getAreaList().then((res) => {
        console.log(res, "省市区");
        if (res.code == 200) {
          this.cityList = res.data;
        }
      });
    },
    // 职位筛选
    positionChange(e) {
      this.userForm.engineering_supervision_id = "";
      if (e == 7) {
        this.userRules.engineering_supervision_id = [
          {
            required: true,
            message: "请选择工程监理",
            trigger: "change",
          },
        ];
      } else {
        delete this.userRules.engineering_supervision_id;
      }
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
      });
    },
    // 获取角色列表
    getRoleList() {
      permissionApi
        .getRoleList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "角色列表");
          if (res.code == 200) {
            this.roleList = res.data.list;
          }
        });
    },
    // 添加用户按钮点击
    addUserModel() {
      this.dialogFormVisible = true;
      this.userFormType = "add";
    },
    // 管理员
    getAdminList() {
      let that = this;
      that.loading = true;
      adminApi
        .getAdminList({
          page: this.page,
          num: this.num,
          keyword: this.searchForm.keyword,
          role_id: this.searchForm.role_id,
          identity: 3,
        })
        .then((res) => {
          console.log(res, "用户列表");
          that.loading = false;
          if (res.code == 200) {
            that.tableData = res.data.list;
            this.multipleSelection = [];
            that.total = res.data.max;
          } else {
            if (res.message == "暂无数据") {
              if (that.page == 1) {
                that.tableData = [];
              }
              return;
            }
            that.$message({
              message: res.message,
              type: "warning",
            });
            that.tableData = [];
            that.total = 0;
          }
        })
        .catch((err) => {
          that.loading = false;
          that.$message({
            message: err.message,
            type: "warning",
          });
        });
    },
    //操作事件
    editEven(row, item) {
      let multipleSelection = this.multipleSelection;
      console.log(multipleSelection)
      switch (item) {
        case "admin_updateAdmin":
          this.saveUser(row);
          break;
        case "admin_deleteAdmin":
          this.delAdmin();
          break;
        case "removeUserLoginRest":
          this.removeLoginRestrictions(row);
          break;
        default:
      }
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getAdminList();
    },
    // 操作用户弹窗 - 提交
    saveSubmit(formName) {
      let userForm = this.userForm;
      console.log(userForm,
        "参数",
        this.userFormType
      );
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 管理员添加修改
          // 优惠比例判断
          if (userForm.discount_ratio) {
            var reg = /^(?:100(?:\.0{1,2})?|[1-9]?\d(?:\.\d{1,2})?)$/;
            if (!reg.test(userForm.discount_ratio)) {
              this.$message.warning("请输入0-100的数值");
              return;
            }
          }
          let formdata = new FormData();
          let data = {
            identity: 3,
            engineering_supervision_id: userForm.engineering_supervision_id,
            name: userForm.name,
            phone: userForm.phone,
            password: userForm.password,
            province_id: userForm.city[0],
            city_id: userForm.city[1],
            county_id: userForm.city[2],
            role_id: userForm.role_id,
            brand_id: userForm.brand_id || 0,
            admin_id: userForm.admin_id,
            discount_ratio: userForm.discount_ratio || 0,
            settlement_discount_ratio: userForm.settlement_discount_ratio || 0,
          };
          if (userForm.imgFile) {
            formdata.append("image", userForm.imgFile || "");
          }
          formdata.append("data", JSON.stringify(data));
          this.submitBtn = true;
          if (this.userFormType == "add") {
            this.addAdmin(formdata);
          } else {
            this.updateAdmin(formdata);
          }
        } else {
          return false;
        }
      });
    },
    // 添加管理员
    addAdmin(userForm) {
      adminApi
        .addAdmin(userForm)
        .then((res) => {
          console.log(res, "addAdmin");
          if (res.code == 200) {
            this.saveUserClose();
            this.getAdminList();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    // 更新管理员
    updateAdmin(userForm) {
      adminApi
        .updAdmin(userForm)
        .then((res) => {
          console.log(res, "updateAdmin");
          if (res.code == 200) {
            this.saveUserClose();
            this.getAdminList();
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    // 编辑用户
    saveUser(row) {
      console.log(row, "saveUser");
      this.userForm.admin_id = row.id;
      this.userForm.name = row.name;
      this.userForm.imgUrl = row.image;
      this.userForm.phone = row.phone;
      this.userForm.city = [row.province_id, row.city_id, row.county_id];
      this.userForm.role_id = row.role_id == 0 ? "" : row.role_id;
      this.userForm.brand_id = row.brand_id == 0 ? "" : row.brand_id;
      this.userForm.discount_ratio = row.discount_ratio;
      this.userForm.settlement_discount_ratio = row.settlement_discount_ratio;
      this.userForm.engineering_supervision_id =
        row.engineering_supervision_id == 0
          ? ""
          : row.engineering_supervision_id;
      this.userFormType = "edit";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
      });
    },
    // 解除登录限制
    removeLoginRestrictions(row) {
      this.$confirm("此操作将解除该用户登录限制, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        adminApi
          .removeLoginRestrictions({
            admin_id: row.id,
          })
          .then((res) => {
            console.log(res, "解除登录限制");
            if (res.code == 200) {
              this.$message.success("操作成功");
              this.getAdminList();
            } else {
              this.$message.warning(res.message);
            }
          })
          .catch((err) => {
            this.$message.warning(err.message);
          });
      }).catch(() => { });
    },
    // 重置密码
    resetPwd(row) {
      this.$prompt('请输入重置的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/,
        inputValue: 'Hzy123789.',
        inputErrorMessage: '密码须8-16位,包含大小写字母、数字'
      }).then(({ value }) => {
        console.log(row, value, "重置密码");
        adminApi.resetPassword({
          admin_id: row.id,
          new_password: value
        }).then((res) => {
          console.log(res, "解除登录限制")
          if (res.code == 200) {
            this.$message.success("操作成功");
          } else {
            this.$message.warning(res.message);
          }
        }).catch((err) => {
          this.$message.warning(err.message);
        });
      }).catch(() => { });
    },
    // 删除用户
    delAdmin() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.name)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        adminApi.delAdmin({
          id_arr
        }).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { })
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/styles/listPage.scss';
@import './index.scss';
</style>
